package com.os.opencv.java.chapter9;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class MinCircle {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/erzhi.jpg", Imgcodecs.IMREAD_GRAYSCALE);

        Mat binary = new Mat();
        Imgproc.threshold(src, binary, 90, 255, Imgproc.THRESH_BINARY);
        HighGui.imshow("binary", binary);
        HighGui.waitKey(0);

        //根据二值图检测轮廓
        List<MatOfPoint> contour = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(binary, contour, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

        //重新获取彩色图像，用于绘制最小外接圆
        src = Imgcodecs.imread("/Users/matt/Pictures/erzhi.jpg");

        //参数准备
        Point center = new Point();
        float[] radius = new float[3];
        Scalar red = new Scalar(0,0,255);
        MatOfPoint2f dst = new MatOfPoint2f();

        for(int i=0; i<contour.size(); i++){
            //将轮廓数据转换为MatOfPoint2f
            contour.get(i).convertTo(dst, CvType.CV_32F);
            //获取最小外接圆
            Imgproc.minEnclosingCircle(dst, center, radius);

            //绘制最小外接圆
            int r = Math.round(radius[0]);
            Imgproc.circle(src, center, r, red, 2);
        }

        //在屏幕上显示绘有最小外接圆的图像
        HighGui.imshow("minCircle", src);
        HighGui.waitKey(0);

        System.exit(0);

    }
}
